package com.lcxw.hxzbapi.controller.appcontroller;


import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbcommon.common.RedisUtils;
import com.lcxw.hxzbcommon.common.SendSms;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lcwx
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin
@Validated
public class CaptchaController {

    @Resource
    RedisUtils redisUtils;


    private Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @PostMapping("/captcha")
    public Response getCaptcha(@RequestBody JSONObject requestBody) {

        String telephone = requestBody.getString("telephone");
        logger.info("telephone : {} want to get captcha,captchaType is {}", telephone,requestBody.getString("captchaType"));
        Response response = new Response();
        String captchaType = requestBody.getString("captchaType");

        if (StringUtil.isEmpty(telephone) || StringUtil.isEmpty(captchaType)) {
            logger.warn("{} or {} is null.",telephone,captchaType);
            response.setCode(ErrorCode.PARAM_ERROR);
            response.setDesc("telephone or captchaType must not be null");
            return response;
        } else if (!StringUtil.checkPhoneNum(telephone)) {
            logger.warn("telNum {} format is incorrect",telephone);
            response.setCode(ErrorCode.NUMBER_ERROR);
            response.setDesc("telephone is incorrect");
            return response;
        }

        //根据验证码类型到redis里获取模板ID
        String redisKeyOfCaptchaType = "captchaType:"+captchaType;
        String templateId = redisUtils.string_get(redisKeyOfCaptchaType);
        if (StringUtil.isEmpty(templateId)){
            logger.warn("captchaType {} is wrong .",captchaType);
            response.setCode(ErrorCode.PARAM_ERROR);
            response.setDesc("captchaType is wrong");
            return response;
        }

        //首先判断redis中该手机号码的该类型验证码是否未过期，未过期则不允许重复获取验证码
        String redisKey = "captchaSuccess:"+captchaType+telephone;
        if (redisUtils.hasKey(redisKey)){
            logger.warn("telephone {} with captchaType {} already exists",telephone,captchaType);
            response.setCode(ErrorCode.NUMBER_ERROR);
            response.setDesc("This type captcha request is repeat,please retry 30s latter.");
            return response;
        }

        //生成随机的4位验证码
        int captchaCode = (int) ((Math.random() * 9 + 1) * 1000);
        String captcha = "[\"" + captchaCode + "\"]";
        HttpResponse smsResponse;
        try {
            smsResponse = new SendSms(telephone, captcha,templateId).send();
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ErrorCode.EXTERNAL_ERROR);
            response.setDesc("send sms fail");
            return response;
        }

        int smsSendStatus = smsResponse.getStatusLine().getStatusCode();
        if (smsSendStatus != 200) {
            logger.error("sms send failed");
            logger.error("smsSendResponse:{}", smsResponse.getEntity());
            response.setCode(ErrorCode.EXTERNAL_ERROR);
            response.setDesc("send sms fail");
            return response;
        }

        logger.info("telephone {} get captcha success,captcha is :{}",telephone,captchaCode);

        //如果短信验证码发送成功，则在redis中标记该号码和验证码类型，存储30S，30秒内不允许重复发送验证码
        redisUtils.string_set(redisKey,captchaCode+"",60);

        Map<String, String> data = new LinkedHashMap<>();
        data.put("captchaType",captchaType);
        data.put("captcha", captchaCode + "");

        response.setCode(0);
        response.setDesc("success");
        response.setData(data);

        return response;
    }
}

